import 'package:OASys/api/RoleApi.dart';
import 'package:OASys/components/FormComponents.dart';
import 'package:OASys/components/scaffoldItem.dart';
import 'package:OASys/entity/MenuVo.dart';
import 'package:OASys/entity/RoleVo.dart';
import 'package:OASys/utils/strUtils.dart';
import 'package:OASys/views/icon/myIcons.dart';
import 'package:flutter/material.dart';

class Rolepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ScaffoldItem('角色管理', MyRolepage());
  }
}

class MyRolepage extends StatefulWidget {
  @override
  _MyRolepageState createState() => _MyRolepageState();
}

class _MyRolepageState extends State<MyRolepage>
    with SingleTickerProviderStateMixin {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  double _addPadding = 30;
  double _queryPadding = 30;
  bool flag = false;
  AnimationController _controller;
  IconData actionIcon = MyIcons.spread;
  List<RoleVo> roleVoList = [];
  int total = 0;
  int page = 1;
  int limit = 10;

  RoleVo andQuery = new RoleVo();
  String loadText = "加载更多";

  final Color disableColor = Color.fromRGBO(230, 162, 60, 1);
  final Color enableColor = Color.fromRGBO(76, 175, 80, 1);
  final String disableText = "禁用";
  final String enableText = "启用";
  @override
  void initState() {
    super.initState();
    getList();
    _controller =
        AnimationController(vsync: this, duration: Duration(milliseconds: 500))
          ..addListener(() {
            setState(() {
              _addPadding = 30 + 100 * _controller.value;
              _queryPadding = 30 + 200 * _controller.value;
            });
          });
  }

  // 更新数据
  void updateData() {
    setState(() {
      resetQuerytData();
      getList();
    });
  }

  // 重置分页查询条件
  void resetQuerytData() {
    setState(() {
      loadText = "加载更多";
      page = 1;
      limit = 10;
      total = 0;
    });
  }

  void getList() {
    RoleApi().getList(
      page,
      limit,
      success: (res) {
        setState(() {
          roleVoList.insertAll(total, res);
          roleVoList.forEach((element) {
            print(element.toJson().toString());
          });
          page++;
          total += res.length;
        });
      },
      error: (err) {
        print(err.toString());
      },
    );
  }

  Future toEdit(RoleVo item) async {
    Navigator.of(context, rootNavigator: true).pop();
    var result = await Navigator.of(context)
        .pushNamed('/roleEdit', arguments: item.toJson());
    if (result == null || !result) {
      print('未添加');
    } else {
      updateData();
      print('添加成功');
    }
  }

  Future toAdd() async {
    var result = await Navigator.of(context).pushNamed('/roleEdit');
    if (result == null || !result) {
      print('未添加');
    } else {
      updateData();
      print('添加成功');
    }
  }

  void remove(int id) {
    RoleApi().remove(
      id,
      success: (res) {
        Navigator.of(context, rootNavigator: true).pop();
        showSuccessMessage(context);
        updateData();
      },
      error: (err) {
        showMessage(context, err.message);
      },
    );
  }

  // 禁用或启用
  void setStatus(int id, int status) {
    RoleApi().setStatus(
      id,
      status,
      success: (res) {
        Navigator.of(context, rootNavigator: true).pop();
        showSuccessMessage(context);
        updateData();
      },
      error: (err) {
        print(err.code);
        showMessage(context, err.message);
      },
    );
  }

  // 加载更多
  void doLoad() {
    RoleApi().list(
      page,
      limit,
      andQuery: andQuery,
      success: (res) {
        if (res == null || res.length == 0) {
          print('无数据');
          setState(() {
            loadText = "没有更多了";
          });
          return;
        }
        setState(() {
          roleVoList.addAll(res);
          total += res.length;
          page++;
          loadText = "加载更多";
        });
        roleVoList.forEach((element) {
          print(element.toJson());
        });
      },
      error: (err) {
        print(err.code);
        print(err.message);
        showMessage(context, err.message);
      },
    );
  }

  List<String> getMenuNameList(List<MenuVo> menuVoList) {
    List<String> strList = [];
    menuVoList.forEach((element) {
      strList.add(element.name);
    });
    return strList;
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  // 查询条件重置
  void reset() {
    var form = formKey.currentState;
    form.reset();
    print('reset');
  }

  // 查询操作
  void doQuery(context) {
    var form = formKey.currentState;
    form.save();
    print(andQuery.toJson());
    if (StrUtils.isBlank(andQuery.name)) {
      showMessage(context, "请输入查询条件");
    } else {
      setState(() {
        if (StrUtils.isBlank(andQuery.name)) {
          andQuery.name = null;
        }
      });
      resetQuerytData();
      RoleApi().list(
        page,
        limit,
        andQuery: andQuery,
        success: (res) {
          setState(() {
            roleVoList = res;
            total += res.length;
            page++;
            if (total == 0) {
              loadText = "暂无数据";
            }
          });
          roleVoList.forEach((element) {
            print(element.toJson());
          });
        },
        error: (err) {
          print(err.code);
          print(err.message);
          showMessage(context, err.message);
        },
      );
      Navigator.of(context, rootNavigator: true).pop();
    }
  }

  // 显示搜索框
  showQuery() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          titlePadding: EdgeInsets.all(0),
          title: Container(
            height: 50,
            alignment: Alignment.center,
            child: Text(
              '查询用户',
              style: TextStyle(color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(3),
                topRight: Radius.circular(3),
              ),
            ),
          ),
          contentPadding: EdgeInsets.all(0),
          content: Container(
            height: 300,
            width: 300,
            decoration: BoxDecoration(
              color: Color.fromRGBO(250, 250, 250, 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              margin: EdgeInsets.only(
                top: 20,
                bottom: 20,
              ),
              height: 260,
              width: 300,
              child: Form(
                key: formKey,
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier("角色名:"),
                        Container(
                          width: 200,
                          child: FormInput(
                            hintText: "请输入角色名",
                            onSave: (value) {
                              andQuery.name = value;
                            },
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          actions: <Widget>[
            RaisedButton(
              color: Color.fromRGBO(33, 150, 243, 1),
              child: Text('查 询'),
              onPressed: () {
                doQuery(context);
              },
            ),
            RaisedButton(
              color: Color.fromRGBO(245, 108, 108, 1),
              child: Text('重 置'),
              onPressed: reset,
            ),
          ],
        );
      },
    );
  }

  // 显示角色信息卡片
  onClick(RoleVo item) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          titlePadding: EdgeInsets.all(0),
          title: Container(
            height: 50,
            alignment: Alignment.center,
            child: Text(
              '角色信息',
              style: TextStyle(color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(3),
                topRight: Radius.circular(3),
              ),
            ),
          ),
          contentPadding: EdgeInsets.all(0),
          content: Container(
            height: 300,
            width: 300,
            decoration: BoxDecoration(
              color: Color.fromRGBO(250, 250, 250, 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              margin: EdgeInsets.only(
                top: 20,
                bottom: 20,
              ),
              height: 260,
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Column(
                  children: [
                    InfoItem('角色名',
                        StrUtils.isNotBlank(item.name) ? item.name : "无"),
                    SizedBox(height: 5),
                    InfoItem('状态', item.statusName),
                    SizedBox(height: 5),
                    InfoListItem('权限', getMenuNameList(item.menuList)),
                  ],
                ),
              ),
            ),
          ),
          actions: <Widget>[
            RaisedButton(
              color: Color.fromRGBO(33, 150, 243, 1),
              child: Text('修 改'),
              onPressed: () {
                toEdit(item);
              },
            ),
            RaisedButton(
              color: Color.fromRGBO(245, 108, 108, 1),
              child: Text('删 除'),
              onPressed: () {
                remove(item.id);
              },
            ),
            RaisedButton(
              color: item.status == 0 ? disableColor : enableColor,
              child: Text(item.status == 0 ? disableText : enableText,
                  style: TextStyle(color: Colors.white)),
              onPressed: () {
                setStatus(item.id, item.status == 0 ? 1 : 0);
              },
            ),
          ],
        );
      },
    );
  }

  /// 按钮收缩展开
  shrinkage() {
    setState(() {
      flag = !flag;
      if (flag) {
        actionIcon = MyIcons.shrink;
        _controller.forward();
      } else {
        actionIcon = MyIcons.spread;
        _controller.reverse();
      }
    });
  }

  /// 构建卡片
  Widget buildListItem(int index) {
    return FlatButton(
      child: Card(
        child: ListTile(
          title: Text(StrUtils.isNotBlank(roleVoList[index].name)
              ? roleVoList[index].name
              : "无"),
          subtitle: Text(StrUtils.isNotBlank(roleVoList[index].statusName)
              ? roleVoList[index].statusName
              : "无"),
        ),
      ),
      onPressed: () {
        onClick(roleVoList[index]);
      },
    );
  }

  //构建加载更多
  Widget buildLoadMore() {
    return FlatButton(
      child: Container(
        child: Text(
          loadText,
          style: TextStyle(color: Colors.blue, fontSize: 12),
        ),
      ),
      onPressed: () {
        doLoad();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          padding: EdgeInsets.only(top: 10, bottom: 10),
          height: 720,
          child: ListView.builder(
            itemCount: total + 1,
            itemBuilder: (BuildContext context, int index) {
              if (index == total) {
                return buildLoadMore();
              }
              return buildListItem(index);
            },
          ),
        ),
        Positioned(
          right: _queryPadding,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.yellow,
              child: Icon(
                MyIcons.query,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: () {
                showQuery();
              },
            ),
          ),
        ),
        Positioned(
          right: _addPadding,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.green,
              child: Icon(
                MyIcons.add,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: () {
                toAdd();
              },
            ),
          ),
        ),
        Positioned(
          right: 30,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.blue,
              child: Icon(
                actionIcon,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: shrinkage,
            ),
          ),
        ),
      ],
    );
  }
}
